package lotterySystem;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JLabel;
import javax.swing.JOptionPane;

import record.DataStorage;
import record.NumbersRecord;
import user.User;

public class Winning {

    // 比对用户选择的号码是否中奖
  	public static List<String> checkWinning(List<String> userRecords, String winningNumber) {
        List<String> winningInfos = new ArrayList<>();
        for (String record : userRecords) {
            String[] userInfo = record.split(",");
            String perName = userInfo[0];
            List<String> numbersOfPerUser = NumbersRecord.fileToList(perName);
            List<String> updateNumbers = new ArrayList<>();
            
            for (String perNumber : numbersOfPerUser) {
                String[] numberInfo = perNumber.split(",");
                StringBuilder combinedNumbers = new StringBuilder();
                
                for (int i = 0; i < numberInfo[0].length(); i += 2) {
                    combinedNumbers.append(numberInfo[0], i, i + 2).append(" ");
                }
                
                String result = calculateResult(combinedNumbers.toString().trim(), winningNumber);
                
                if (!result.equals("未获奖")) {
                    String winningInfo = perName + "," + numberInfo[0] + "," + result;
                    winningInfos.add(winningInfo);
                }
                
                updateNumbers.add(numberInfo[0] + "," + result);
            }

            NumbersRecord.listToFile(updateNumbers, perName);
        }
        
        return winningInfos;
    }
  	//计算奖项
    private static String calculateResult(String perNumber, String winningNumber) {
        int matchedCount = 0;

        for (int i = 0; i < perNumber.length(); i += 3) { // 每两位数字之间有一个空格，所以步长为3
            if (winningNumber.contains(perNumber.substring(i, i + 2))) { 
                matchedCount++;
            }
        }

        if (matchedCount == 7) { 
            return "特等奖";
        } else if (matchedCount == 6) { 
            return "一等奖";
        } else if (matchedCount == 5){ 
            return "二等奖";
        } else if(matchedCount ==4){
            return "三等奖";
        } else{
            return "未中奖";
        }
    }
    
	public static void notifyFirstLogin(List<String> numbers, User currentUser,List<String> userRecords,JLabel balanceLabel) {
		
        if(numbers.size()==0){
            JOptionPane.showMessageDialog(null, "欢迎来到大乐透抽奖平台，在这里一夜暴富不是梦!!!\n              快去购买你的第一张彩票吧");
            return;
        }
        int totalPrize = 0;
        StringBuilder message = new StringBuilder();
        boolean flag=true;
        for (String number : numbers) {
            int price=0;
            String[] numberInfo = number.split(",");
            
            if(!numberInfo[1].equals("未中奖")){
                message.append(numberInfo[0]).append("\n恭喜用户：").append(currentUser.getUsername()).append(":\n");
                message.append("中将号码 ").append(numberInfo[0]).append(" 获得 ").append(numberInfo[1]);
                flag=false;
            }
            
         
            if(numberInfo[1].equals("特等奖")){
                 price=1000;
            }else  if (numberInfo[1].equals("一等奖")) { 
                 price=500;
            } else if (numberInfo[1].equals("二等奖")) { 
                price=250;
            } else if (numberInfo[1].equals("三等奖")){ 
                price=100;
            }
            // 计算总奖金
            totalPrize += price;
        }
        if(flag){
            message.append("很遗憾，您购买的彩票均未获奖！");
        }
        // 弹出消息框
        int option = JOptionPane.showOptionDialog(null, message.toString(), "中将提醒", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
                null, new Object[]{"领取奖金"}, "领取");

        if (option == 0) { // 如果点击了“领取”按钮
            JOptionPane.showMessageDialog(null, "已成功领取总共 " + totalPrize + " 元", "领取成功", JOptionPane.INFORMATION_MESSAGE);
            double amount=Double.parseDouble(Integer.toString(totalPrize) );
            currentUser.recharge(currentUser, amount,userRecords);
            DataStorage.updateBalance(currentUser.getUsername(),currentUser.getBalance(),userRecords);
            balanceLabel.setText("余额：" + currentUser.getBalance());// 删除文件里对应号码
            File file = new File(currentUser.getUsername()+"_number_records.txt");  // 替换为实际文件路径
            try {
                List<String> lines = Files.readAllLines(file.toPath());
                
                lines.removeAll(numbers);
                Files.write(file.toPath(), lines);
                
                numbers.clear();  // 清空列表里对应号码
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
}
    // private static boolean isFirstTimeLogin(String username) {
        
    //     return true;  
    // }
 
}
